import React, { Component } from 'react'
import axios from 'axios'
import PubSub from 'pubsub-js'
import { Button } from 'antd'

export default class Search extends Component {

  search = async () => {
    // 获取用户的输入(连续解构赋值+重命名)
    const { inputRef: { value: keyWord } } = this

    // 发送请求前通知List更新状态
    PubSub.publish('axiosPubtest', { isFirst: false, isLoading: true })
    //#region 发送网络请求 axios
    //#endregion
    axios.get(`/api/search/users?q=${keyWord}`).then(
      response => {
        //请求成功后通知List更新状态
        PubSub.publish('axiosPubtest', { isLoading: false, users: response.data.items, err: '' })
      },
      error => {
        //请求失败后通知List更新状态
        PubSub.publish('axiosPubtest', { isLoading: false, err: error.message })
      }
    )
    
    // fetch 发送请求
    // fetch(`/api/search/users?q=${keyWord}`).then(response => {
    //   return response.json()
    // }).then(response =>
    //   PubSub.publish('axiosPubtest', { isLoading: false, users: response.items, err: '' })
    // ).catch(() => {
    //   PubSub.publish('axiosPubtest', { isLoading: false, err: '请求失败！' })
    // })
    //发送网络请求---使用fetch发送（优化）
    // try {
    //   const response = await fetch(`/api/search/users?q=${keyWord}`)
    //   const data = await response.json()
    //   PubSub.publish('atguigu', { isLoading: false, users: data.items })
    // } catch (error) {
    //   PubSub.publish('atguigu', { isLoading: false, err: error.message })
    // }
  }
  // 键盘事件
  handleKeyUp = (event) => {
    // 获取keyCode，target
    const { keyCode, target } = event
    // 判断是不是回车键
    if (keyCode !== 13) return
    // 判断数据不能为空，并清除两边空格
    if (target.value.trim() === '') {
      alert('不能为空')
      return
    }
    this.search()
    // 清空输入框
    // target.value = ''
  }

  render() {
    return (
      <section className="jumbotron">
        <h3 className="jumbotron-heading">Search Github Users</h3>
        <div>
          <input ref={c => this.inputRef = c} onKeyUp={this.handleKeyUp} type="text" placeholder="enter the name you search" />&nbsp;
          <Button type='primary' onClick={this.search}>Search</Button>
        </div>
      </section>
    )
  }
}
